package DAOs;

import DAOs.exceptions.NonexistentEntityException;
import Entity.Collaborator;
import Entity.ReforestationZone;
import Entity.Visit;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityNotFoundException;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

/**
 *
 * @author USUARIO
 */
public class VisitJpaController implements Serializable {

    public VisitJpaController(EntityManagerFactory emf) {
        this.emf = emf;
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Visit visit) {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            ReforestationZone reforestationZone = visit.getReforestationZone();
            if (reforestationZone != null) {
                reforestationZone = em.getReference(reforestationZone.getClass(), reforestationZone.getId());
                visit.setReforestationZone(reforestationZone);
            }
            Collaborator visitor = visit.getVisitor();
            if (visitor != null) {
                visitor = em.getReference(visitor.getClass(), visitor.getId());
                visit.setVisitor(visitor);
            }
            em.persist(visit);
            if (reforestationZone != null) {
                reforestationZone.getVisits().add(visit);
                reforestationZone = em.merge(reforestationZone);
            }
            if (visitor != null) {
                visitor.getVisits().add(visit);
                visitor = em.merge(visitor);
            }
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Visit visit) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Visit persistentVisit = em.find(Visit.class, visit.getId());
            ReforestationZone reforestationZoneOld = persistentVisit.getReforestationZone();
            ReforestationZone reforestationZoneNew = visit.getReforestationZone();
            Collaborator visitorOld = persistentVisit.getVisitor();
            Collaborator visitorNew = visit.getVisitor();
            if (reforestationZoneNew != null) {
                reforestationZoneNew = em.getReference(reforestationZoneNew.getClass(), reforestationZoneNew.getId());
                visit.setReforestationZone(reforestationZoneNew);
            }
            if (visitorNew != null) {
                visitorNew = em.getReference(visitorNew.getClass(), visitorNew.getId());
                visit.setVisitor(visitorNew);
            }
            visit = em.merge(visit);
            if (reforestationZoneOld != null && !reforestationZoneOld.equals(reforestationZoneNew)) {
                reforestationZoneOld.getVisits().remove(visit);
                reforestationZoneOld = em.merge(reforestationZoneOld);
            }
            if (reforestationZoneNew != null && !reforestationZoneNew.equals(reforestationZoneOld)) {
                reforestationZoneNew.getVisits().add(visit);
                reforestationZoneNew = em.merge(reforestationZoneNew);
            }
            if (visitorOld != null && !visitorOld.equals(visitorNew)) {
                visitorOld.getVisits().remove(visit);
                visitorOld = em.merge(visitorOld);
            }
            if (visitorNew != null && !visitorNew.equals(visitorOld)) {
                visitorNew.getVisits().add(visit);
                visitorNew = em.merge(visitorNew);
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Long id = visit.getId();
                if (findVisit(id) == null) {
                    throw new NonexistentEntityException("The visit with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Long id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Visit visit;
            try {
                visit = em.getReference(Visit.class, id);
                visit.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The visit with id " + id + " no longer exists.", enfe);
            }
            ReforestationZone reforestationZone = visit.getReforestationZone();
            if (reforestationZone != null) {
                reforestationZone.getVisits().remove(visit);
                reforestationZone = em.merge(reforestationZone);
            }
            Collaborator visitor = visit.getVisitor();
            if (visitor != null) {
                visitor.getVisits().remove(visit);
                visitor = em.merge(visitor);
            }
            em.remove(visit);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Visit> findVisitEntities() {
        return findVisitEntities(true, -1, -1);
    }

    public List<Visit> findVisitEntities(int maxResults, int firstResult) {
        return findVisitEntities(false, maxResults, firstResult);
    }

    private List<Visit> findVisitEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Visit.class));
            Query q = em.createQuery(cq);
            Query q1 = em.createNativeQuery("Select ID from visit");
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
                q1.setMaxResults(maxResults);
                q1.setFirstResult(firstResult);
            }
            List<Visit> visitsList = q.getResultList();
            for (int i = 0; i < visitsList.size(); i++) {
                visitsList.get(i).setId((Long) q1.getResultList().get(i));
            }
            return visitsList;
        } finally {
            em.close();
        }
    }

    public Visit findVisit(Long id) {
        EntityManager em = getEntityManager();
        try {
            Visit visit = em.find(Visit.class, id);
            visit.setId(id);
            return visit;
        } finally {
            em.close();
        }
    }

    public int getVisitCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Visit> rt = cq.from(Visit.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
}
